<template>
  <div>
    <!-- 面包屑导航条 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统中心</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-form :model="searchForm" class="demo-form-inline" >
        <el-row :gutter="20">
          <el-form-item>
            <el-col :span="4">
              <el-input placeholder="姓名" v-model="searchForm.fullName"></el-input>
            </el-col>
            <el-col :span="11">
              <el-date-picker placeholder="入职日期(开始)" type="date" v-model="searchForm.startDate"></el-date-picker>
                -
              <el-date-picker placeholder="入职日期(结束)" type="date" v-model="searchForm.endDate"></el-date-picker>
            </el-col>
            <el-button @click="searchUser" plain type="info">搜索</el-button>
            <el-button @click="userFormVisible=true" type="primary">添加用户</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-table
        :data="userList"
        stripe
        style="width: 100%">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          label="头像">
          <template slot-scope="scope">
            <img  v-if="scope.row.image!=null" :src="'api/user/download/'+scope.row.image" width="50px" height="50px">
          </template>
        </el-table-column>
        <el-table-column
          label="用户名"
          prop="userName"
          width="180">
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="fullName"
          width="180">
        </el-table-column>
        <el-table-column
          label="性别">
          <template slot-scope="scope">
            {{scope.row.sex | sexFit}}
          </template>
        </el-table-column>
        <el-table-column
          label="手机号"
          prop="tel">
        </el-table-column>
        <el-table-column
          label="邮箱"
          prop="email" width="160">
        </el-table-column>
        <el-table-column
          label="入职日期"
          prop="hiredate">
          <template slot-scope="scope">
            {{scope.row.hiredate | datefmt('YYYY/MM/DD')}}
          </template>
        </el-table-column>
        <el-table-column
          label="是否启用">
          <template slot-scope="scope">
            <span style="display:none;">  {{scope.row.state=(scope.row.isEnable==1)}}</span>
            <el-switch
              @change="updateIsEnable(scope.row,scope.row.isEnable)" v-model="scope.row.state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button @click="getUser(scope.row.id)" size="small" type="text" v-if="scope.row.isEnable==0">编辑
            </el-button>
            <el-button @click=" assignmentRole(scope.row)" size="small" type="text">分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page.pagenum"
        :page-size="page.pagesize"
        :page-sizes="[5, 10, 20, 40]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <el-dialog :close-on-click-modal="false" :title="userForm.id==null?'添加用户':'编辑用户'" :visible.sync="userFormVisible"
                 @closed="crearUserForm"> <!--用户表单框 -->
        <el-form :model="userForm" label-width="70px" >
          <el-row :gutter="22">
            <el-col :span="11">
              <el-form-item label="头像">
                <el-upload
                  class="avatar-uploader"
                  action="/api/user/upload"
                  :headers="auth"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="userForm.image!=null" :src="'/api/user/download/'+userForm.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="22">
            <el-col :span="11">
              <el-form-item label="用户名">
                <el-input v-model="userForm.userName"  size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="入职日期">
                <el-date-picker placeholder="选择日期" style="width: 100%;" type="date"
                                v-model="userForm.hiredate"  size="small"> </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="22">
            <el-col :span="11">
              <el-form-item label="姓名">
                <el-input v-model="userForm.fullName"  size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="性别">
                <el-radio :label="0" v-model="userForm.sex">男</el-radio>
                <el-radio :label="1" v-model="userForm.sex">女</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="22">
            <el-col :span="11">
              <el-form-item label="手机号">
                <el-input v-model="userForm.tel"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="邮箱">
                <el-input v-model="userForm.email"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="dialog-footer" slot="footer">
          <el-button @click="userFormVisible = false">取 消</el-button>
          <el-button @click="saveUser()" type="primary">确 定</el-button>
        </div>
      </el-dialog>

<!--     分配角色-->
      <el-dialog :close-on-click-modal="false" title="分配角色" :visible.sync="userRoleVisible"
                 @closed="crearUserRole"> <!--用户表单框 -->
        <el-form label-width="100px" >
          <el-row>
            <el-col :span="14">
              <el-form-item label="用户">
                <el-input v-model="userFullName" size="small" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item label="角色">
                <el-select v-model="roleIds" multiple filterable placeholder="请选择">
                  <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="dialog-footer" slot="footer">
          <el-button @click="userRoleVisible = false">取 消</el-button>
          <el-button @click="saveUserRole()" type="primary">确 定</el-button>
        </div>
      </el-dialog>

    </el-card>

  </div>

</template>

<script>

  export default {
    name: "UserList",
    data() {
      return {
        userFormVisible: false,
        userForm: {},
        searchForm: {fullName:"",startDate:null,endDate:null},
        userList: [],
        page: {
          pagenum: 0,
          pagesize: 5
        },
        total: 0,
        userRoleVisible:false,
        userId:null,
        userFullName:'',
        roleIds:[],
        roleList:[],
        auth:{token:null}
      }
    },
    methods: {
      handleAvatarSuccess(res, file) {//上传完成后回调
           this.userForm.image = res.result.path;
      },
      beforeAvatarUpload(file) {//=,=== 和 == 比较的是内容
        const isJPG = file.type === 'image/jpeg'|| file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      saveUserRole:function(){//保存用户的角色关系
        var formdata=new FormData();
          formdata.append("userId",this.userId);
          formdata.append("roleIds",this.roleIds);
        this.$http.post("/userRole/save",formdata).then((res)=>{
          if (res.data.success) {
            this.$message.success(res.data.message);
          }else{
            this.$message.error(res.data.message);
          }
          this.userRoleVisible=false;
        });
      },
      crearUserRole:function(){//清空数据
          this.userId=null;
          this.userFullName='';
          this.roleIds=[];
      },
      assignmentRole: async function (row) {//分配角色
        this.userRoleVisible = true;
        this.userId = row.id; //获取用户的id
        this.userFullName = row.fullName; //获取用户的全名

        let res = await this.$http.get("/role/getRoles"); //同步请求
        this.roleList = res.data.result;

        this.$http.get("/userRole/getByUserId/" + row.id).then((res) => {  //获取当前用户的角色id
          if (res.data.success) {
            this.roleIds = res.data.result;
          } else {
            this.$message.error(res.data.message);
          }
        })

      },
      updateIsEnable: function (row, id) {//状态修改
        if (row.state) {
          row.isEnable = 1;
        } else {
          row.isEnable = 0;
        }
        this.$http.get("/user/updateIsEnable/"+row.id+"/"+row.isEnable).then((res) => {
          if (res.data.success) {
            this.$message.success(res.data.message);
          }else{
            this.$message.error(res.data.message);
          }
        });
      },
      getUser: function (id) {//查询当前id的用户
        this.$http.get("/user/get/" + id).then((res) => {
          if (res.data.success) {
            this.userForm = res.data.result //赋值
            this.userFormVisible = true //显示dialog框
          } else {
            this.$message.error(res.data.message);
          }
        });
      },
      searchUser: function () {//用户列表
        this.$http.post("/user/list/" + this.page.pagenum + "/" + this.page.pagesize, this.searchForm).then((res) => {
          this.userList = res.data.result.list;
          this.total = res.data.result.total;
        });
      },
      handleSizeChange: function (val) {
        this.page.pagesize = val;
        this.searchUser();
      },
      handleCurrentChange: function (val) {
        this.page.pagenum = val;
        this.searchUser();
      },
      crearUserForm: function () {
        //清空数据
        this.userForm = {}
      },
      saveUser: function () { //用户保存
        this.$http.post("/user/save", this.userForm).then((res) => {
          //如何提示
          if (res.data.success) {
            this.$message({
              message: res.data.message,
              type: 'success'
            });
          } else {
            this.$message.error(res.data.message);
          }
          //关闭dialog框
          this.userFormVisible = false
          //重新加载列表
          this.searchUser()
        });
      }
    },
    filters: {
      sexFit: function (v1) {
        if (v1 == '0') return '男'
        if (v1 == '1') return '女'
      }
    },
    mounted() {
      this.searchUser();
      //设置token
      this.auth.token=sessionStorage.getItem("token");
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
